<template>
  <div class="loginBox">
    <el-row>
      <el-col class="content">
        <el-form
          label-width="80px"
          :model="loginForm"
          ref="loginForm"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" autofocus></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              @keyup.enter.native="doLogin"
            ></el-input>
          </el-form-item>
          <el-form-item label="登录失败" v-show="loginForm.message != ''">
            <p style="margin: 0">{{ loginForm.message }}</p>
          </el-form-item>
          <el-form-item class="to_right">
            <el-button type="success" @click="doLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import isEmpty from "@/utils/isEmpty";
import axios from "@/request";

export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        message: "",
      },
      rules: {
        username: [{ required: true, message: "用户名必填" }],
        password: [{ required: true, message: "密码必填" }],
      },
    };
  },
  methods: {
    doLogin() {
      let loading = Loading.service({
        target: ".content",
        text: "正在登录...",
        background: "rgba(236, 245, 255, 0.2)",
      });
      // 登陆前校验
      let passed = false;
      this.$refs.loginForm.validate((result, faildFields) => {
        passed = result;
      });
      // 校验不通过不发起登录请求
      if (!passed) {
        loading.close();
        return;
      }
      axios
        .post("/auth/login", {
          username: this.loginForm.username,
          password: this.loginForm.password,
        })
        .then((res) => {
          if (res.data.code == 200) {
            sessionStorage.setItem("authUser", JSON.stringify(res.data.data));
            this.$store.dispatch("userModule/updateUser", res.data.data);
            loading.close();
            this.$router.push({ name: "good" });
          } else {
            this.loginForm.message = res.data.data;
            loading.close();
          }
        })
        .catch((error) => {
          loading.close();
        });
    },
  },
};
</script>

<style scoped>
.loginBox {
  height: 100%;
}

.to_right {
  margin-top: 20px;
  float: right;
}

.content {
  background-color: rgba(200, 200, 200, 0.6);
  padding: 30px 50px 20px 20px;
}
</style>